import type { HookFetchPlugin } from 'hook-fetch';
import { ElMessage } from 'element-plus';
import hookFetch from 'hook-fetch';
import { sseTextDecoderPlugin } from 'hook-fetch/plugins';
import router from '@/routers';

interface BaseResponse {
  code: number;
  data: never;
  msg: string;
  rows: never;
}

export const request = hookFetch.create<BaseResponse, 'data' | 'rows'>({
  baseURL: import.meta.env.VITE_API_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  plugins: [sseTextDecoderPlugin({ json: true, prefix: 'data:' })],
});

function jwtPlugin(): HookFetchPlugin<BaseResponse> {
  return {
    name: 'jwt',
    beforeRequest: async (config) => {
      try {
        // 动态导入 useUserStore，避免在模块加载时调用
        const { useUserStore } = await import('@/stores');
        const userStore = useUserStore();
        
        config.headers = new Headers(config.headers);
        if(userStore.token) {
          config.headers.set('authorization', `Bearer ${userStore.token}`);
          config.headers.set('token', userStore.token);
        }
        config.data && ((config.data as any)['_t'] = new Date().getTime())
      } catch (error) {
        console.warn('无法获取用户 store，跳过 token 设置:', error);
        config.headers = new Headers(config.headers);
        config.data && ((config.data as any)['_t'] = new Date().getTime())
      }
      return config;
    },
    afterResponse: async (response) => {
      // console.log(response);
      if (response.result?.code === 200 || response.result?.code === 0) {
        return response;
      }
      
      // 处理403逻辑
      if (response.result?.code === 403) {
        // 跳转到403页面（确保路由已配置）
        router.replace({
          name: '403',
        });
        ElMessage.error(response.result?.msg);
        return Promise.reject(response);
      }
      
      // 处理401逻辑
      if (response.result?.code === 401) {
        try {
          // 动态导入 useUserStore，避免在模块加载时调用
          const { useUserStore } = await import('@/stores');
          const userStore = useUserStore();
          // 如果没有权限，退出，且弹框提示登录
          userStore.logout();
          userStore.openLoginDialog();
        } catch (error) {
          console.warn('无法获取用户 store，跳过登出处理:', error);
        }
      }
      
      ElMessage.error(response.result?.msg);
      return Promise.reject(response);
    },
  };
}

request.use(jwtPlugin());

export const post = request.post;

export const get = request.get;

export const put = request.put;

export const del = request.delete;

export default request;
